//package com.plian.system.service.tb.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.common.status.CheckStatus;
//import com.plian.system.config.YthTaskObserver;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.entity.tb.*;
//import com.plian.system.mapper.tb.TopicImplementMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.search.TokenSearch;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.service.sys.message.IApprovalMessageService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.tb.*;
//import com.plian.system.service.yth.IConferenceDecisionExecuteBaseService;
//import com.plian.system.vo.tb.TopicImplementVO;
//import com.plian.system.vo.tb.TripleMeetingVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.tb.TopicImplementWrapper;
//import com.plian.system.wrapper.tb.TripleMeetingWrapper;
//import lombok.AllArgsConstructor;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * @Author: Take-off
// * @Description: TODO 议题实施管理
// * @Date: 2022/12/28 2:24 PM
// * @Version: 1.0
// **/
//@Service
//@AllArgsConstructor
//public class TopicImplementServiceImpl extends BaseServiceImpl<TopicImplementMapper, TopicImplement> implements ITopicImplementService, BaseFlowService {
//
//    private final ITopicImplementDetailService implementDetailService;
//
//    private final TopicImplementWrapper topicImplementWrapper;
//
//    private final ITripleMeetingService tripleMeetingService;
//
//    private final TripleMeetingWrapper tripleMeetingWrapper;
//
//    private final ITripleMeetingTopicService meetingTopicService;
//
//    private final ITopicRelevanceService topicRelevanceService;
//
//    private final IConferenceDecisionExecuteBaseService decisionExecuteBaseService;
//
//    private final IOrgService orgService;
//
//    private final ISysUserService userService;
//
//    private IApprovalMessageService approvalMessageService;
//    @Override
//    public boolean saveOrUpdate(TopicImplement topicImplement) {
//        if (!Optional.ofNullable(topicImplement.getId()).isPresent()) {
//            topicImplement.setFormType(String.valueOf(FormTypeConstant.PF_TRIPLE_TOPIC_IMPLEMENT));
//        }
//        if (!Optional.ofNullable(topicImplement.getImplementReportStatus()).isPresent()){
//            topicImplement.setImplementReportStatus(2);
//        }
//        return super.saveOrUpdate(topicImplement);
//    }
//
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            TopicImplement topicImplement = getById(id);
//            if (topicImplement == null) {
//                return false;
//            }
//        }
//        boolean result = super.deleteLogic(ids);
//        if (result){
//            implementDetailService.deleteByParentId(ids);
//        }
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean submit(TopicImplement topicImplement) {
//        boolean result = saveOrUpdate(topicImplement);
//        if (result){
//            List<TopicImplementDetail> implementDetails = topicImplement.getImplementDetails();
//            if (CollectionUtil.isNotEmpty(implementDetails)){
//                for (TopicImplementDetail implementDetail : implementDetails){
//                    if (implementDetail.getId() != null &&
//                            Optional.ofNullable(implementDetail.getIsDeleted()).isPresent() && implementDetail.getIsDeleted().intValue() == 1) {
//                        implementDetailService.removeById(implementDetail.getId());
//                    }else {
//                        implementDetail.setBaseImplementId(topicImplement.getId());
//                        implementDetailService.saveOrUpdate(implementDetail);
//                    }
//                }
//            }
//        }
//        return result;
//    }
//
//    @Override
//    public TopicImplementVO getDetailObj(TopicImplement topicImplement){
//        TopicImplementVO topicImplementVO = new TopicImplementVO();
//        if (Optional.ofNullable(topicImplement.getId()).isPresent()){
//            topicImplementVO = topicImplementWrapper.entityToVO(getById(topicImplement.getId()));
//        }
//        //议题信息
//        Long topicId = null;
//        if (Optional.ofNullable(topicImplement.getTopicId()).isPresent()){
//            topicId = topicImplement.getTopicId();
//        }else {
//            topicId = topicImplementVO.getTopicId();
//        }
//
//        TripleMeetingTopic topic = meetingTopicService.getById(topicId);
//        topicImplementVO.setTopicName(topic.getTopicName());
//
//        //会议
//        TripleMeetingVO meeting = tripleMeetingWrapper.entityToVO(tripleMeetingService.getById(topic.getBaseMeetingId()));
//        topicImplementVO.setMeetingName(meeting.getMeetingName());
//        topicImplementVO.setMeetingTypeName(meeting.getMeetingTypeName());
//
//        //议题详情
//        List<TopicRelevance> relevances = topicRelevanceService.list(new LambdaQueryWrapper<TopicRelevance>().eq(TopicRelevance::getTopicId, topicId));
//        topicImplementVO.setTopicRelevances(relevances);
//
//        //责任落实
//        List<TopicImplementDetail> detailList = implementDetailService.list(new LambdaQueryWrapper<TopicImplementDetail>().eq(TopicImplementDetail::getBaseImplementId, topicImplementVO.getId()));
//        topicImplementVO.setImplementDetails(detailList);
//
////        //实施信息-详情
////        List<ImplementReport> implementReports = implementReportService.list(new LambdaQueryWrapper<ImplementReport>().eq(ImplementReport::getBaseImplementId, topicImplementVO.getId()));
////        topicImplementVO.setImplementReports(implementReports);
//
//        return topicImplementVO;
//    }
//
//    @Override
//    public boolean submitImplement(TopicImplement topicImplement){
//        TopicImplement oldImplement = getById(topicImplement.getId());
//        oldImplement.setImplementReportUser(topicImplement.getImplementReportUser());
//        oldImplement.setImplementReportTime(topicImplement.getImplementReportTime());
//        oldImplement.setImplementReportStatus(topicImplement.getImplementReportStatus());
//        oldImplement.setResponsibilityUser(topicImplement.getResponsibilityUser());
//        oldImplement.setResponsibilityDept(topicImplement.getResponsibilityDept());
//        oldImplement.setTrueFinishTime(topicImplement.getTrueFinishTime());
//        oldImplement.setRemarks(topicImplement.getRemarks());
//
//        boolean result = saveOrUpdate(topicImplement);
//        return result;
//    }
//
//    @Override
//    public List<TripleMeetingTopic> getAllTopic(){
//        List<TripleMeetingTopic> tripleMeetingTopics = new ArrayList<>();
//        //已经记录的会议
//        List<TripleMeeting> meetings = tripleMeetingService.list(new LambdaQueryWrapper<TripleMeeting>().eq(TripleMeeting::getStatus, 3));
//        //会议议题
//        if (CollectionUtil.isNotEmpty(meetings)){
//             tripleMeetingTopics = meetingTopicService.list(new LambdaQueryWrapper<TripleMeetingTopic>().in(TripleMeetingTopic::getBaseMeetingId, meetings.stream().map(TripleMeeting::getId).collect(Collectors.toList())));
//        }
//        return tripleMeetingTopics;
//    }
//
//    @Override
//    public ListResult<TopicImplementVO> list(Query query) {
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs()==null&&query.getDescs()==null){
//            query.setDescs("create_time");
//        }
//        QueryWrapper<TopicImplement> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new TopicImplement()), entityList
//        );
//        IPage<TopicImplement> pages = page(Condition.getPage(query), queryWrapper);
//        List<TopicImplementVO> topicImplementVOS = topicImplementWrapper.entityToVO(pages.getRecords());
//        //set 时间
//        if (CollectionUtil.isNotEmpty(topicImplementVOS)){
//            //setvo
//            List<TripleMeetingTopic> topics = meetingTopicService.list(new LambdaQueryWrapper<TripleMeetingTopic>().in(TripleMeetingTopic::getId, topicImplementVOS.stream().map(TopicImplementVO::getTopicId).collect(Collectors.toList())));
//            if (CollectionUtil.isNotEmpty(topics)){
//                List<TripleMeeting> meetings = tripleMeetingService.list(new LambdaQueryWrapper<TripleMeeting>().in(TripleMeeting::getId, topics.stream().map(TripleMeetingTopic::getBaseMeetingId).collect(Collectors.toList())));
//                topicImplementVOS.forEach(vo ->{
//                    List<TripleMeetingTopic> topicList = topics.stream().filter(m -> vo.getTopicId().equals(m.getId())).collect(Collectors.toList());
//                    if (CollectionUtil.isNotEmpty(topicList)){
//                        TripleMeetingTopic topic = topicList.get(0);
//                        vo.setTopicName(topic.getTopicName());
//                        if (CollectionUtil.isNotEmpty(meetings)){
//                            List<TripleMeeting> meetingList = meetings.stream().filter(m -> topic.getBaseMeetingId().equals(m.getId())).collect(Collectors.toList());
//                            if (CollectionUtil.isNotEmpty(meetingList)){
//                                TripleMeeting tripleMeeting = meetingList.get(0);
//                                vo.setMeetingName(tripleMeeting.getMeetingName());
//                            }
//                        }
//                    }
//                });
//            }
//
//            List<TopicImplementDetail> details = implementDetailService.list(new LambdaQueryWrapper<TopicImplementDetail>()
//                    .in(TopicImplementDetail::getBaseImplementId, topicImplementVOS.stream().map(TopicImplementVO::getId).collect(Collectors.toList())));
//            topicImplementVOS.forEach(vo ->{
//                //set 时间
//                if (CollectionUtil.isNotEmpty(details)){
//                    List<TopicImplementDetail> detailList = details.stream().filter(m -> m.getBaseImplementId().equals(vo.getId())).collect(Collectors.toList());
//                    if (CollectionUtil.isNotEmpty(detailList)){
//                        List<Date> dates = detailList.stream().filter(m -> Optional.ofNullable(m.getFinishTime()).isPresent()).sorted(Comparator.comparing(TopicImplementDetail::getFinishTime).reversed()).map(TopicImplementDetail::getFinishTime).collect(Collectors.toList());
//                        if (CollectionUtil.isNotEmpty(dates)){
//                            vo.setFinishTime(dates.get(0));
//                        }
//                    }
//
//                }
//            });
//        }
//
//        ListResult<TopicImplementVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//        listResult.setList(topicImplementVOS);
//        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
//        return listResult;
//    }
//
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,"");
//
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState,String comment) {
//        return handleStatus(Long.valueOf(id), formState,comment);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<TopicImplement> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(TopicImplement::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<TopicImplement> tripleMeetings = list(queryWrapper);
//        List<TopicImplementVO> topicImplementVOS = topicImplementWrapper.entityToVO(tripleMeetings);
//        List<PageData> pageDataList = new ArrayList<>();
//        try{
//            if (CollectionUtil.isNotEmpty(topicImplementVOS)){
//                for (TopicImplementVO vo : topicImplementVOS){
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getReportOfficeName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getReportOffice());
//                    pd.put("formType", FormTypeConstant.PF_TRIPLE_TOPIC_IMPLEMENT);
//                    pd.put("orgName", vo.getReportOfficeName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.PF_TRIPLE_TOPIC_IMPLEMENT);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED, "");
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id          主键
//     * @param updateStatus  更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus,String comment) {
//        try {
//            TopicImplement tripleMeeting = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH){
//                tripleMeeting.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                tripleMeeting.setApprovedTime(now);
//            }
//            tripleMeeting.setStatus(updateStatus);
//            updateById(tripleMeeting);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String saveTopicImplementList(String data){
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<TopicImplement> dataList = JSON.parseArray(data, TopicImplement.class);
//        if (CollectionUtil.isNotEmpty(dataList)){
//            //根据datasourceIds 查询出所有的数据
//            List<TopicImplement> list = list(new LambdaQueryWrapper<TopicImplement>().in(TopicImplement::getDataSourceId, dataList.stream().map(TopicImplement::getDataSourceId).toArray()));
//            //如果数据库中有数据，就更新，没有就新增
//            for (TopicImplement entity:dataList){
//                //id重复略过
//                if (CollectionUtil.isNotEmpty(list)){
//                    List<String> olIds = list.stream().map(TopicImplement::getDataSourceId).collect(Collectors.toList());
//                    String dataSourceId = entity.getDataSourceId();
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)){
//                        for (TopicImplement oldEntity:list){
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())){
//                                //判断status是否为0，如果是0，就更新，不是0，就不更新
//                                if (CheckStatus.checkCode(oldEntity.getStatus())){
//                                    successIds.add(dataSourceId);
//                                    entity.setId(oldEntity.getId());
//                                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                                    saveOrUpdate(entity);
//                                    list.remove(oldEntity);
//                                    break;
//                                }else {
//                                    failIds.add(dataSourceId);
//                                    failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//                                    break;
//                                }
//                            }
//                        }
//                    }else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//                        saveOrUpdate(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                }else {
//                    //如果数据库中没有数据，就新增
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                    saveOrUpdate(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        } else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    @Override
//    @YthTaskObserver
//    public boolean saveImplementByDataBase(String date){
//        boolean flag = true;
//        Date start = DateUtil.parse(date, DateUtil.PATTERN_DATE);
//        //获取数据
////        List<TopicImplement> topicImplements = decisionExecuteBaseService.getAllProject(start, DateUtil.plusDays(start, 1));
//        List<TopicImplement> topicImplements = decisionExecuteBaseService.getAllProject(null,null);
//        remove(Wrappers.<TopicImplement>lambdaQuery().eq(TopicImplement::getDataSource,3));
//        Map<String, String> userSource = userService.getSourceId();
//        if (CollectionUtil.isNotEmpty(topicImplements)){
//            //获取修改数据
//            List<TopicImplement> oldImplements = list(Wrappers.<TopicImplement>lambdaQuery().eq(TopicImplement::getDataSource, YthConstant.DATA_NINGBO)
//                    .in(TopicImplement::getDataSourceId, topicImplements.stream().map(TopicImplement::getDataSourceId).collect(Collectors.toList())));
//            List<TripleMeeting> tripleMeetings = tripleMeetingService.list(Wrappers.<TripleMeeting>lambdaQuery().eq(TripleMeeting::getDataSource, YthConstant.DATA_NINGBO));
//            List<TripleMeetingTopic> meetingTopics = meetingTopicService.list(Wrappers.<TripleMeetingTopic>lambdaQuery().eq(TripleMeetingTopic::getDataSource, YthConstant.DATA_NINGBO));
//
//            if (CollectionUtil.isNotEmpty(oldImplements)){
//                //删除子集
//                List<Long> ids = oldImplements.stream().map(TopicImplement::getId).collect(Collectors.toList());
//                if (CollectionUtil.isNotEmpty(ids)){
//                    implementDetailService.deleteByParentId(ids);
//                }
//            }
//            for (TopicImplement implement:topicImplements){
//                if (CollectionUtil.isNotEmpty(meetingTopics)){
//                    meetingTopics.stream().filter( m -> implement.getTopicId().toString().equals(m.getDataSourceId())).findFirst().ifPresent( topic ->{
//                        implement.setTopicId(topic.getId());
//                        //会议
//                        if (CollectionUtil.isNotEmpty(tripleMeetings)){
//                            tripleMeetings.stream().filter( m -> topic.getBaseMeetingId().equals(m.getId())).findFirst().ifPresent(meet -> {
//                                implement.setMeetingName(meet.getMeetingName());
//                            });
//                        }
//                    });
//                }
//
//                String userId = userSource.get(implement.getReportUser());
//                if (StringUtils.isNotBlank(userId)){
//                    implement.setReportUser(userId);
//                }
//                flag = submit(implement);
//            }
//        }
//        return flag;
//    }
//
//
//}
